/*
** 非标: 需配置config文件
*  接口文档：https://device.harmonyos.com/cn/docs/documentation/DevicePartner-References/obtain-bluetooth-status-0000001077309158
*/
import config from "./Config";
import storeManage from "../store/index";
export default class BlueToothManage {
    constructor() {
        console.log("BlueToothManage => constructor");
        //是否ios设备
        this.isIOS = false;
        //ios设备id
        this.iosDeviceId = "";
        //android设备id
        this.deviceId = "";
        this.serviceId = config.serviceId;
        this.characteristicId = config.characteristicId;
        this.writeCharacteristicId = config.writeCharacteristicId;
        //定时器
        this.timer = null;
        // 0：初始未连接状态 1：连接中 2：已连接 3: 连接超时
        this.status = 0;
        // 蓝牙是否打开
        this.isBleAdapterOpened = false;
    }

    /**
    * 初始化
    */
    init() {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => init");
            this.getSystemInfo();
        }
    }

    /**
    * 是否存在hilink
    */
    isExsitHilink() {
        if (!window.hilink) {
            console.log("BlueToothManage => no hilink ");
            return false;
        } else {
            return true;
        }
    }

    /**
    * 获取手机系统信息,判断手机操作系统是 Android 还是 iOS
    */
    getSystemInfo() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => getSystemInfo");
            window.getSystemInfoSyncCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BlueToothManage getSystemInfo => " + data);
                storeManage.commit("ble/setSystemInfo", data);
                self.isIOS = data.platform === "iOS" ? true : false;
                self.listeningBleChange();
                self.getBleState();
            };
            window.hilink.getSystemInfoSync("getSystemInfoSyncCallback");
        }
    }

    /**
    * 监听蓝牙变化,主动打开或关闭蓝牙会触发
    */
    listeningBleChange() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => listeningBleChange");
            window.onBlueToothAdapterStateChangeCallback = (res) => {
                // 监听蓝牙状态回调函数
                let data = JSON.parse(res);
                console.log("BlueToothManage => listeningBleChange => " + data);
                //蓝牙适配器是否可用
                let available = data.available;
                //是否正在搜索设备
                //let discovering = data.discovering;
                if (available) {
                    self.isBleAdapterOpened = true;
                    self.getRegisteredDevice();
                } else {
                    self.changeStatus(0);
                    self.clearTimer();
                    self.timer = null;
                    self.isBleAdapterOpened = false;
                }
            };
            window.hilink.onBluetoothAdapterStateChange("onBlueToothAdapterStateChangeCallback");
        }
    }

    /**
    * 获取当前蓝牙模块状态
    */
    getBleState() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => getBleState");
            window.getBlueToothAdapterStateCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BlueToothManage => getBleState => " + data);
                //蓝牙适配器是否可用
                let available = data.available;
                //是否正在搜索设备
                //let discovering = data.discovering;
                //错误码：0, 90001
                //let errCode = data.errCode;
                if (available) {
                    self.getRegisteredDevice();
                } else {
                    self.openBlueTooth();
                }
            };
            window.hilink.getBluetoothAdapterState("getBlueToothAdapterStateCallback");
        }
    }

    /**
    * 获取宫格页面中选择的已注册的设备
    */
    getRegisteredDevice() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => getRegisteredDevice");
            self.changeStatus(1);
            window.getCurrentRegisteredDeviceCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BlueToothManage => getRegisteredDevice => " + data);
                let id = data.deviceId;
                let deviceInfo = data.hilinkDeviceEntity;
                storeManage.commit("ble/setDeviceInfo", deviceInfo);
                if (self.isIOS) {
                    // ios
                    self.iosDeviceId = id;
                    self.getIOSdevices();
                } else {
                    // android
                    self.deviceId = id;
                    self.connectDevice();
                }
            };
            window.hilink.getCurrentRegisteredDevice("getCurrentRegisteredDeviceCallback");
            self.createTimer();
        }
    }

    /**
    * IOS发现附近蓝牙
    */
    getIOSdevices() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => getIOSdevices ");
            window.onBluetoothDeviceFoundCallBack = (info) => {
                let data = JSON.parse(info);
                console.log("BlueToothManage => getIOSdevices => " + data);
                let mac = "";
                if (data.advertisData) {
                    let advertisData = data.advertisData;
                    advertisData = advertisData.replace(/\s+/g, "");
                    advertisData = advertisData.slice(-13, -1).toLocaleUpperCase();
                    mac = self.analysisMac(advertisData);
                }
                if (self.iosDeviceId === data.deviceId || mac === self.iosDeviceId) {
                    console.log("BlueToothManage => getIOSdevices => 匹配到的设备 => " + data.deviceId);
                    self.stopBleDevicesDiscovery();
                    self.deviceId = data.deviceId;
                    self.connectDevice();
                }
            };
            window.hilink.onBluetoothDeviceFound("onBluetoothDeviceFoundCallBack");
            window.hilink.startBluetoothDevicesDiscovery([], 0, 1);
        }
    }

    /**
    * 停止搜索蓝牙设备
    */
    stopBleDevicesDiscovery() {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => stopBleDevicesDiscovery ");
            window.hilink.stopBluetoothDevicesDiscovery();
        }
    }

    /**
    * 连接设备
    */
    connectDevice() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => connectDevice ");
            window.onBLEConnectionStateChangeCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BlueToothManage => connectDevice => " + data);
                if (data.connected) {
                    // 连接成功
                    self.bleServicesDiscovered();
                    console.log('connectDevice=>','连接成功');
                } else {
                    // 重新连接。
                    self.reConnect();
                    self.createTimer();
                    console.log('connectDevice=>','连接失败');
                }
            };
            // 监听蓝牙设备连接结果
            window.hilink.onBLEConnectionStateChange("onBLEConnectionStateChangeCallback");
            if (self.isIOS) {
                window.hilink.createBLEConnection(self.iosDeviceId);
            } else {
                window.hilink.createBleConnection(self.deviceId, 2); // 指定蓝牙连接方式
            }
        }
    }

    /**
    * 重新连接
    */
    reConnect() {
        console.log("BlueToothManage => reConnect ");
        this.changeStatus(1);
        if (this.deviceId) {
            this.connectDevice();
            return false;
        }
        this.init();
    }

    /**
    * 设备连接成功通知上层
    */
    bleServicesDiscovered() {
        let self = this;
        if (self.isExsitHilink) {
            console.log("BlueToothManage => bleServicesDiscovered ");
            window.changeServiceDiscoverState = (res) => {
                let data = JSON.parse(res);
                console.log(
                    "BlueToothManage => bleServicesDiscovered => changeServiceDiscoverState " +
                    data
                );
                console.log(
                    "设备连接成功通知上层" +
                    JSON.stringify(data)
                );
                
                if (data.errCode === 0) {
                    let changeStatus = window.hilink.notifyBLECharacteristicValueChange(
                        self.deviceId,
                        self.serviceId,
                        self.characteristicId,
                        true
                    );
                    console.log(
                        "BlueToothManage => bleServicesDiscovered => notifyBLECharacteristicValueChange " +
                        changeStatus
                    );
                    if (changeStatus === 0 && self.isBleAdapterOpened) {
                        self.watchBleData();
                        self.changeStatus(2);
                        self.clearTimer();
                    }
                }
            };
            window.hilink.onBLEServicesDiscovered("changeServiceDiscoverState");
        }
    };

    /**
    * 监听蓝牙数据改变
    */
    watchBleData() {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => watchBleData ");
            window.onBLECharacteristicValueChangeCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BlueToothManage => watchBleData => " + data);
                storeManage.commit("ble/setCharactValueChangeRes", data);
            };
            window.hilink.onBLECharacteristicValueChange("onBLECharacteristicValueChangeCallback");
        }
    };

    /**
    * 打开手机蓝牙
    */
    openBlueTooth() {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => openBlueTooth ");
            window.hilink.openBluetoothAdapter();
        }
    }

    /**
    * 断开蓝牙连接
    */
    closeBLEConnection() {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => closeBLEConnection ");
            window.hilink.closeBLEConnection(this.deviceId || this.iosDeviceId);
        }
    };

    /**
    * 发送蓝牙数据
    * @param {string} data - 需要发送的数据
    * @param {Function} callback - 回调
    */
    send(data, callback) {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => sendData " + data);
            window.writeBLECharacteristicValueCallback = (res) => {
                if (callback) callback(res);
            };
            window.hilink.writeBLECharacteristicValue(this.deviceId, this.serviceId, this.writeCharacteristicId,
                data, "writeBLECharacteristicValueCallback");
        }
    };

    analysisMac(str) {
        if (str) {
            let result = [];
            for (let i = 0; i < str.length; i += 2) {
                result.push(str[i] + str[i + 1]);
            }
            return result.join(":");
        }
        return "";
    };

    /* 设置超时 */
    createTimer() {
        console.log("BlueToothManage => createTimer ");
        let self = this;
        if (self.timer !== null) {
            return false;
        }
        if (self.isIOS) {
            self.stopBleDevicesDiscovery();
        }
        self.timer = setTimeout(function () {
            self.changeStatus(3);
            self.clearTimer();
            self.timer = null;
        }, 30 * 1000);
    };

    clearTimer() {
        console.log("BlueToothManage => clearTimer ");
        clearTimeout(this.timer);
    };

    changeStatus(status) {
        console.log("BlueToothManage => changeStatus " + status);
        this.status = status;
        storeManage.commit('ble/setBleSatuts', status);
    };

    /**
    * 设置标题栏是否可见
    * 
    * @param {boolean} visible - 是否显示
    */
    setTitleVisible(visible) {
        if (this.isExsitHilink()) {
            console.log("BlueToothManage => setTitleVisible " + visible);
            window.hilink.setTitleVisible(visible);
        }
    }
}
